package icraf.carbon.gui;

import static icraf.carbon.gui.MenuFactory.MenuProperty.GENERAL_ABOUT;
import static icraf.carbon.gui.MenuFactory.MenuProperty.MODEL_BG;
import static icraf.carbon.gui.MenuFactory.MenuProperty.MODEL_CB;
import static icraf.carbon.gui.MenuFactory.MenuProperty.MODEL_COSTB_TOTAL;
import static icraf.carbon.gui.MenuFactory.MenuProperty.MODEL_CSTOCK;
import static icraf.carbon.gui.MenuFactory.MenuProperty.MODEL_DYNAMIC;
import static icraf.carbon.gui.MenuFactory.MenuProperty.MODEL_EMISSION;
import static icraf.carbon.gui.MenuFactory.MenuProperty.MODEL_LANDUSE;
import static icraf.carbon.gui.MenuFactory.MenuProperty.MODEL_LANDUSE_SCENARIO;
import static icraf.carbon.gui.MenuFactory.MenuProperty.MODEL_MAIN;
import static icraf.carbon.gui.MenuFactory.MenuProperty.MODEL_MODIF;
import static icraf.carbon.gui.MenuFactory.MenuProperty.MODEL_NPV;
import static icraf.carbon.gui.MenuFactory.MenuProperty.MODEL_OPCOST;
import static icraf.carbon.gui.MenuFactory.MenuProperty.MODEL_OUTPUT;
import static icraf.carbon.gui.MenuFactory.MenuProperty.MODEL_OUTPUT_CBU_MATRIX;
import static icraf.carbon.gui.MenuFactory.MenuProperty.MODEL_OUTPUT_MATRIX;
import static icraf.carbon.gui.MenuFactory.MenuProperty.MODEL_SCENARIO;
import static icraf.carbon.gui.MenuFactory.MenuProperty.MODEL_SIMULATION;
import static icraf.carbon.gui.MenuFactory.MenuProperty.MODEL_SUMMARY;
import static icraf.carbon.gui.MenuFactory.MenuProperty.MODEL_TPM;
import static icraf.carbon.gui.MenuFactory.MenuProperty.PROJECT;
import static icraf.carbon.gui.MenuFactory.MenuProperty.PROJECT_ABATEMENT;
import static icraf.carbon.gui.MenuFactory.MenuProperty.PROJECT_BG_EMISSION;
import static icraf.carbon.gui.MenuFactory.MenuProperty.PROJECT_COSTB;
import static icraf.carbon.gui.MenuFactory.MenuProperty.PROJECT_COSTB_TOTAL;
import static icraf.carbon.gui.MenuFactory.MenuProperty.PROJECT_COSTB_UNIT;
import static icraf.carbon.gui.MenuFactory.MenuProperty.PROJECT_CSTOCK;
import static icraf.carbon.gui.MenuFactory.MenuProperty.PROJECT_ECONOMIC;
import static icraf.carbon.gui.MenuFactory.MenuProperty.PROJECT_EMISSION_ADD;
import static icraf.carbon.gui.MenuFactory.MenuProperty.PROJECT_INPUT;
import static icraf.carbon.gui.MenuFactory.MenuProperty.PROJECT_LANDUSE;
import static icraf.carbon.gui.MenuFactory.MenuProperty.PROJECT_LCOVER_CHANGE;
import static icraf.carbon.gui.MenuFactory.MenuProperty.PROJECT_LCOVER_ZONE_CBU_MATRIX;
import static icraf.carbon.gui.MenuFactory.MenuProperty.PROJECT_MODIF_EMISSION;
import static icraf.carbon.gui.MenuFactory.MenuProperty.PROJECT_NPV;
import static icraf.carbon.gui.MenuFactory.MenuProperty.PROJECT_OUTPUT;
import static icraf.carbon.gui.MenuFactory.MenuProperty.PROJECT_SPATIAL;
import static icraf.carbon.gui.MenuFactory.MenuProperty.PROJECT_SUMMARY;
import static icraf.carbon.gui.MenuFactory.MenuProperty.PROJECT_SUMMARY_EMISSION;
import static icraf.carbon.gui.MenuFactory.MenuProperty.PROJECT_SUMMARY_OPCOST;
import static icraf.carbon.gui.MenuFactory.MenuProperty.PROJECT_ZONATION;
import icraf.carbon.core.Config.ConfigItem;
import icraf.carbon.core.Project;
import icraf.carbon.core.Zone.DataType;
import icraf.carbon.core.ZoneList;
import icraf.carbon.gui.InputLabelPanel.LabelListener;
import icraf.carbon.gui.MenuFactory.MenuProperty;
import icraf.carbon.gui.chart.AbacusPanel;
import icraf.carbon.gui.model.MatrixIterationPanel;
import icraf.carbon.gui.model.ModelEmissionBgPanel;
import icraf.carbon.gui.model.ModelEmissionModPanel;
import icraf.carbon.gui.model.ModelIterationPanel;
import icraf.carbon.gui.model.ModelOutputCBUPanel;
import icraf.carbon.gui.model.ModelOutputPanel;
import icraf.carbon.gui.model.ModelPanel;
import icraf.carbon.gui.model.ModelScenarioPanel;
import icraf.carbon.gui.model.ModelSummaryPanel;
import icraf.carbon.model.MatrixCBUPanel;
import icraf.carbon.model.ModelProject;
import icraf.common.gui.MenuAdapter;
import icraf.common.gui.MenuGenerator;
import icraf.common.gui.MenuGenerator.IconModel;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTabbedPane;
import javax.swing.SwingWorker;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import com.vlsolutions.swing.docking.DockKey;
import com.vlsolutions.swing.docking.Dockable;

public class CardPanel implements Dockable {
	

	public class TabListener implements ChangeListener {

		@Override
		public void stateChanged(ChangeEvent evt) {
			JTabbedPane p = (JTabbedPane) evt.getSource();
			activeTabIndex = p.getSelectedIndex();
		}

	}

	class DefaultOptPanel extends JPanel implements ActionListener {
		private static final long serialVersionUID = 8010365377254772411L;
		MenuAdapter[] menu;
		

		public DefaultOptPanel(MenuAdapter[] menu) {
			this.menu = menu;
			setLayout(new BorderLayout());
			JPanel listPanel = new JPanel(new GridBagLayout());
			this.add(listPanel);
			//setLayout(new GridBagLayout());
			GridBagConstraints c = new GridBagConstraints();

			c.insets = new Insets(5, 5, 5, 5);
			c.fill = GridBagConstraints.BOTH;

			c.gridx = 0;
			c.gridy = 0;

			for (MenuAdapter m : menu) {
				c.gridy++;
				listPanel.add(MenuGenerator.createButton(m, this, true, IconModel.ICON16),
						c);
			}
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			for (int i = 0; i < menu.length; i++) {
				if (menu[i].isAction(e)) {
					projectDock.setSelection(selectedProject, menu[i]);
					return;
				}
			}
		}
	}

	class HolderPanel extends JPanel implements ActionListener {
		private static final long serialVersionUID = 8010365377254772411L;
		private JLabel titleLabel;

		public HolderPanel(String label, JComponent mainComponent) {
			setLayout(new BorderLayout());
			add(mainComponent, BorderLayout.CENTER);

			titleLabel = new JLabel("  " + label);
			titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD));
			JButton backB = MenuGenerator.createButton(
					MenuProperty.GENERAL_BACK, this, true, IconModel.ICON16);
			backB.setMargin(new Insets(0, 5, 0, 5));
			backB.setContentAreaFilled(false);
			backB.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
			JPanel headerP = new JPanel(new BorderLayout());
			headerP.setOpaque(true);
			headerP.setBackground(Color.white);
			headerP.add(titleLabel);
			headerP.add(backB, BorderLayout.EAST);
			add(headerP, BorderLayout.NORTH);
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			if (MenuProperty.GENERAL_BACK.isAction(e)) {
				projectDock.showSelectedParentNode();
			}
		}

		public void setTitle(String text) {
			titleLabel.setText("  " + text);
		}
	}


	
	class ImportListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			int opt = JOptionPane.showConfirmDialog((Component) e.getSource(), 
						MenuProperty.PROJECT_IMPORT_WARNING.getAccessibleDescription(), 
						MenuProperty.PROJECT_IMPORT_WARNING.getLabel(), 
						JOptionPane.OK_CANCEL_OPTION,
						JOptionPane.WARNING_MESSAGE);
			if(opt == JOptionPane.OK_OPTION) {
				ImportRawDataPanel importDataPanel = new ImportRawDataPanel(mainPanel);
				selectedProject = importDataPanel.importRawData(selectedProject);
			}
		}

	}
	
	private static String BLANK = "blank";
	private static String MODEL_DEFAULT = "model";
	private static String PROGRESS = "progress";
	private AboutAbacus aboutPanel = new AboutAbacus(false);
	private CardLayout card;
	private JPanel chartContainer = new JPanel(new BorderLayout());
	private MenuAdapter defaultKey = GENERAL_ABOUT;
	private InputLabelPanel inputLabelPanel = new InputLabelPanel();

	private HolderPanel holderModelOut;
	private HolderPanel holderModelOutCBU;
	private InputZonePanel inputAreaPanel = new InputZonePanel();
	private InputBelowgroundEmission inputBelowgroundEmission = new InputBelowgroundEmission();
	private InputModifiedEmission inputModifiedEmission = new InputModifiedEmission();
	private InputCBUPanel inputCBUPanel = new InputCBUPanel();
	private LCMatrixTabCBUPanel inputCostBPanel = new LCMatrixTabCBUPanel();
	private MatrixPanel inputCStockPanel = new MatrixPanel(new LCZTableModel());

	private InputLandUsePanel inputLandUsePanel = new InputLandUsePanel();
	private InputTransitionMatrix inputTransitionMatrix;
	private boolean isUpdateArea = false;
	private DockKey key = new DockKey();
	private HolderPanel holderOutMatrixCBU;
	private InputNPVPanel inputNPVPanel = new InputNPVPanel();
	private JPanel mainPanel = new JPanel();
	
	private MenuAdapter[] menuInput = { PROJECT_SPATIAL, PROJECT_ECONOMIC,
			PROJECT_EMISSION_ADD };
	private MenuAdapter[] menuSpatial = { PROJECT_LANDUSE, PROJECT_ZONATION,
			PROJECT_LCOVER_CHANGE, PROJECT_CSTOCK };
	private MenuAdapter[] menuEconomy = { PROJECT_COSTB_UNIT, PROJECT_NPV,
			PROJECT_COSTB };
	private MenuAdapter[] menuBgEmit = { PROJECT_BG_EMISSION,
			PROJECT_MODIF_EMISSION };
	
	private MenuAdapter[] menuOutput = { 
			PROJECT_SUMMARY_EMISSION, 
			PROJECT_COSTB_TOTAL,
			PROJECT_SUMMARY_OPCOST,
			PROJECT_SUMMARY, 
			PROJECT_ABATEMENT};

	private MenuAdapter[] menuProject = { PROJECT_INPUT, PROJECT_OUTPUT,
			MODEL_SIMULATION };
	private MenuAdapter[] menuScenario = { MODEL_MAIN, MODEL_TPM,
			MODEL_LANDUSE_SCENARIO, MODEL_DYNAMIC };
	
	private MenuAdapter[] menuDynamic = {MODEL_CSTOCK, MODEL_NPV, MODEL_CB, MODEL_BG, MODEL_MODIF};
	
	private MenuAdapter[] menuSimulation = { MODEL_SCENARIO, MODEL_OUTPUT };
	private MenuAdapter[] menuModelOutput = { MODEL_SUMMARY, MODEL_LANDUSE,
			MODEL_EMISSION, MODEL_COSTB_TOTAL, MODEL_OPCOST };

	
	

	// *********Model***********
	private ModelOutputPanel modelIterationPanel = new ModelOutputPanel();
	private ModelOutputCBUPanel modelOutputCBUPanel = new ModelOutputCBUPanel();
	private ModelPanel modelPanel;
	private ModelSummaryPanel modelSummaryPanel = new ModelSummaryPanel();
	private ModelScenarioPanel modelTM;
	private ModelScenarioPanel modelTPM;
	private LCMatrixOutputPanel outputEmissionPanel = new LCMatrixOutputPanel();
	private LCMatrixOutputCBUPanel outputMatrixCBUPanel = new LCMatrixOutputCBUPanel();

	private MatrixIterationPanel<LCZTableModel> cstockIterationPanel = new MatrixIterationPanel<LCZTableModel>(new LCZTableModel());
	@SuppressWarnings("rawtypes")
	private MatrixCBUPanel<MatrixIterationPanel> npvIterationPanel = new MatrixCBUPanel<MatrixIterationPanel>(new MatrixIterationPanel<LCZTableModel>(new LCZTableModel()));
	
	private MatrixCBUPanel<ModelIterationPanel> cbIterationPanel = new MatrixCBUPanel<ModelIterationPanel>(new ModelIterationPanel());
	private ModelIterationPanel bgIterationPanel = new ModelEmissionBgPanel();
	private ModelIterationPanel modifIterationPanel = new ModelEmissionModPanel();
	
	
	private ProjectTreePanel projectDock;

	private MenuAdapter selectedMenu;
	private Object selectedObject;
	private Project selectedProject;
	private SummaryPanel summaryPanel = new SummaryPanel();
	private TabListener listener = new TabListener();
	private int activeTabIndex = 0;

	public CardPanel(final ProjectTreePanel projectDock) {
		this.projectDock = projectDock;
		
		key.setFloatEnabled(true);
		key.setCloseEnabled(false);
		key.setAutoHideEnabled(false);
		card = new CardLayout();
		mainPanel.setLayout(card);
		mainPanel.add(aboutPanel, defaultKey.toString());

		modelPanel = new ModelPanel(getProjectDock().getAbacusMain().getStatusBar());
		modelTM = modelPanel.getModelTransitionPanel();
		modelTPM = modelPanel.getModelTPMPanel();
		
		inputCStockPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
		DefaultOptPanel pOptPanel = new DefaultOptPanel(menuProject);
		inputLabelPanel.addMenuPanel(pOptPanel);
		inputLabelPanel.setLabelListener(new LabelListener() {
			
			@Override
			public void labelChanged() {
				projectDock.refreshTreeNode();
				
			}
		});
		inputTransitionMatrix = new InputTransitionMatrix(projectDock);

		String s[] = {
				MenuProperty.PROJECT_ZONE_PARTITION.getLabel(), 
				MenuProperty.PROJECT_NET_EMISSION.getLabel(), 
				MenuProperty.PROJECT_TOTAL_EMISSION.getLabel(), 
				MenuProperty.PROJECT_TOTAL_SEQ.getLabel() };
		outputEmissionPanel.setLabel(s);
		outputEmissionPanel.setZoneAreaScale(false);
		outputEmissionPanel.setCornerSetting(
				MenuProperty.UNIT_EMISSION_HA.getLabel(),
				MenuProperty.UNIT_EMISSION.getLabel(), true);

		modelPanel.setProjectManager(projectDock.getProjectManager());

		addCardElement(PROJECT, inputLabelPanel);
		addCardElement(PROJECT_INPUT, new DefaultOptPanel(menuInput));
		DefaultOptPanel optSpatialPanel = new DefaultOptPanel(menuSpatial);
		JButton importRawB = MenuGenerator.createButton(MenuProperty.PROJECT_IMPORT_RAW, new ImportListener(), true, IconModel.ICON16);
		JPanel impP = new JPanel(new FlowLayout(FlowLayout.LEFT));
		impP.add(importRawB);
		optSpatialPanel.add(impP, BorderLayout.NORTH);
		addCardElement(PROJECT_SPATIAL, optSpatialPanel);
		
		addCardElement(PROJECT_ECONOMIC, new DefaultOptPanel(menuEconomy));
		addCardElement(PROJECT_EMISSION_ADD, new DefaultOptPanel(menuBgEmit));
		addCardElement(PROJECT_ZONATION, inputAreaPanel);
		addCardElement(PROJECT_LANDUSE, inputLandUsePanel);
		addCardElement(PROJECT_LCOVER_CHANGE, inputTransitionMatrix);

		addCardElement(PROJECT_BG_EMISSION, inputBelowgroundEmission);
		addCardElement(PROJECT_MODIF_EMISSION, inputModifiedEmission);

		addCardElement(PROJECT_COSTB_UNIT, inputCBUPanel);
		addCardElement(PROJECT_COSTB, inputCostBPanel);
		addCardElement(PROJECT_NPV, inputNPVPanel);
		holderOutMatrixCBU = addCardElement(PROJECT_LCOVER_ZONE_CBU_MATRIX,
				outputMatrixCBUPanel);

		addCardElement(PROJECT_CSTOCK, inputCStockPanel);
		addCardElement(PROJECT_SUMMARY_EMISSION, outputEmissionPanel);
		addCardElement(PROJECT_SUMMARY, summaryPanel);
		addCardElement(PROJECT_ABATEMENT, chartContainer);
		addCardElement(PROJECT_OUTPUT, new DefaultOptPanel(menuOutput));
		inputAreaPanel.setProjectTreePanel(projectDock);

		addCardElement(MODEL_SIMULATION, new DefaultOptPanel(menuSimulation));
		addCardElement(MODEL_SCENARIO, new DefaultOptPanel(menuScenario));
		addCardElement(MODEL_MAIN, modelPanel);
		addCardElement(MODEL_TPM, modelTPM);
		addCardElement(MODEL_LANDUSE_SCENARIO, modelTM);
		
		addCardElement(MODEL_DYNAMIC, new DefaultOptPanel(menuDynamic));
		addCardElement(MODEL_CSTOCK, cstockIterationPanel);
		addCardElement(MODEL_NPV, npvIterationPanel);
		addCardElement(MODEL_CB, cbIterationPanel);
		addCardElement(MODEL_BG, bgIterationPanel);
		addCardElement(MODEL_MODIF, modifIterationPanel);
		cbIterationPanel.setEditable(true);
		bgIterationPanel.setEditable(true);
		modifIterationPanel.setEditable(true);
		
		modelTPM.setProjectTreePanel(projectDock);
		modelTM.setProjectTreePanel(projectDock);
		modelPanel.setProjectTreePanel(projectDock);

		addCardElement(MODEL_SUMMARY, modelSummaryPanel);

		addCardElement(MODEL_OUTPUT, new DefaultOptPanel(menuModelOutput));
		holderModelOut = addCardElement(MODEL_OUTPUT_MATRIX,
				modelIterationPanel);
		holderModelOutCBU = addCardElement(MODEL_OUTPUT_CBU_MATRIX,
				modelOutputCBUPanel);

		mainPanel.add(new JPanel(), BLANK);
		MenuAdapter[] menu = { MODEL_MAIN };
		mainPanel.add(new HolderPanel(MenuProperty.MODEL_ERROR.getLabel(),
				new DefaultOptPanel(menu)), MODEL_DEFAULT);
				
		JProgressBar pbar = new JProgressBar();
		JLabel l = new JLabel(MenuProperty.MODEL_WAIT.getLabel());
		l.setAlignmentX(JLabel.CENTER_ALIGNMENT);
		pbar.setIndeterminate(true);
		JPanel p = new JPanel();
		p.setBorder(BorderFactory.createEmptyBorder(50, 50, 50, 50));
		p.setLayout(new BoxLayout(p, BoxLayout.PAGE_AXIS));
		p.add(Box.createVerticalGlue());
		p.add(l);
		p.add(pbar);
		p.add(Box.createVerticalGlue());
		mainPanel.add(p, PROGRESS);
		
		
		inputTransitionMatrix.addZoneTabListener(listener);
		inputCostBPanel.addZoneTabListener(listener);
		inputBelowgroundEmission.addZoneTabListener(listener);
		inputModifiedEmission.addZoneTabListener(listener);
		
		outputEmissionPanel.addZoneTabListener(listener);
		outputMatrixCBUPanel.addZoneTabListener(listener);
		
		modelTM.addZoneTabListener(listener);
		modelTPM.addZoneTabListener(listener);
		modelIterationPanel.addZoneTabListener(listener);
		modelOutputCBUPanel.addZoneTabListener(listener);
	
	}


	private HolderPanel addCardElement(MenuAdapter m, JComponent panel) {
		HolderPanel holder = new HolderPanel(m.getAccessibleDescription(),
				panel);
		mainPanel.add(holder, m.toString());
		return holder;
	}

	private boolean checkArea() {
		double precision = ConfigItem.PRECISION_MAX.getValueDouble();
		double precision10 = (float)Math.pow(10, precision);
		ZoneList zones = selectedProject.getZoneList();
		double total = 0;
		boolean invalid = false;
		for (int i = 0; i < zones.getSize(); i++) {
			total = zones.get(i).getValueTotal(DataType.LANDCOVER_CHANGE, null);
			//double prec = 10000000;
			total = Math.round(total * precision10) / precision10;
			if ((total != 1) && (total != 0)) {
				invalid = true;
				break;
			}
		}
		return invalid;
	}

	@Override
	public Component getComponent() {
		return mainPanel;
	}

	@Override
	public DockKey getDockKey() {
		return key;
	}

	/**
	 * @return the projectDock
	 */
	protected ProjectTreePanel getProjectDock() {
		return projectDock;
	}

	public MenuAdapter getSelectedMenu() {
		return selectedMenu;
	}

	public Object getSelectedObject() {
		return selectedObject;
	}

	public Project getSelectedProject() {
		return selectedProject;
	}

	
		
	private void doShowProperty(Object childObj, MenuAdapter pi, Project project) {	
		int selectedTab = activeTabIndex;
		if (isUpdateArea) {
			updateAreaSize(false);
		} else if (selectedMenu == PROJECT_LCOVER_CHANGE) {
			if (checkArea()) {
				int opt = JOptionPane
						.showConfirmDialog(
								inputTransitionMatrix,
								MenuProperty.PROJECT_ZONE_CHANGES.getAccessibleDescription(),
								MenuProperty.PROJECT_ZONE_CHANGES.getLabel(),
								JOptionPane.OK_CANCEL_OPTION);
				if (opt == JOptionPane.YES_OPTION) {
					updateAreaSize(true);
				} else {
					selectedMenu = pi;
					projectDock.setSelection(selectedProject,
							PROJECT_LCOVER_CHANGE);
					return;
				}
			}
		}

		if (project == null) {
			card.show(mainPanel, defaultKey.toString());
			this.getDockKey().setName(defaultKey.getLabel());
			return;
		}

		selectedObject = childObj;
		selectedMenu = pi;
		selectedProject = project;

		key.setName(pi.getLabel() + " [" + project.getLabel() + "]");
		key.setIcon(pi.getIcon(IconModel.ICON16));

		if (pi == MODEL_TPM || pi == MODEL_LANDUSE_SCENARIO
				|| pi == MODEL_SUMMARY || pi == MODEL_COSTB_TOTAL
				|| pi == MODEL_EMISSION || pi == MODEL_LANDUSE
				|| pi == MODEL_OPCOST || pi == MODEL_CSTOCK 
				|| pi ==  MODEL_NPV || pi ==  MODEL_CB 
				|| pi ==  MODEL_BG || pi ==  MODEL_MODIF) {
			ModelProject m = project.getModelProject();
			if (m == null) {
				card.show(mainPanel, MODEL_DEFAULT);
				return;
			}
		}

		
		if (pi == MenuProperty.PROJECT) {
			inputLabelPanel.setProject(project);
		} else if (pi == GENERAL_ABOUT) {
		} else if (pi == PROJECT_ZONATION) {
			inputAreaPanel.setProject(project);
		} else if (pi == PROJECT_LANDUSE) {
			inputLandUsePanel.setProject(project);
		} else if (pi == PROJECT_CSTOCK) {
			((LCZTableModel) inputCStockPanel.getMatrixTableModel())
					.setProject(project, DataType.CARBONSTOCK, null);
		} else if (pi == PROJECT_COSTB_UNIT) {
			inputCBUPanel.setProject(project);
		} else if (pi == PROJECT_NPV) {
			inputNPVPanel.setProject(project, DataType.NPV);
		} else if (pi == PROJECT_COSTB) {
			inputCostBPanel
					.setProject(project, DataType.COSTBENEFIT_CONVERSION);
			inputCostBPanel.setCornerSetting(MenuProperty.UNIT_CB_HA.getLabel(),
					MenuProperty.UNIT_CB.getLabel(), true);
			inputCostBPanel.setZoneAreaScale(true);
			inputCostBPanel.setEditable(true);
			inputCostBPanel.selectZoneTab(selectedTab);
			
		} else if (pi == PROJECT_COSTB_TOTAL) {
			outputMatrixCBUPanel
					.setProject(project, DataType.COSTBENEFIT_TOTAL);
			holderOutMatrixCBU.setTitle(pi.getAccessibleDescription());
			outputMatrixCBUPanel.setCornerSetting(MenuProperty.UNIT_CB_HA.getLabel(),
					MenuProperty.UNIT_CB.getLabel(), true);
			outputMatrixCBUPanel.setZoneAreaScale(false);
			String s[] = {
					MenuProperty.PROJECT_ZONE_PARTITION.getLabel(), 
					MenuProperty.PROJECT_NET_CB.getLabel(),
					MenuProperty.PROJECT_BENEFIT.getLabel(),
					MenuProperty.PROJECT_COST.getLabel()};
			outputMatrixCBUPanel.setLabel(s);
			
			JTabbedPane tabPanel = outputMatrixCBUPanel.getTabPanel();
			for (int i = 0; i < tabPanel.getTabCount(); i++) {
				LCMatrixOutputPanel c = (LCMatrixOutputPanel) tabPanel
						.getComponentAt(i);
				c.getZonePanel().setMenuDetail(
						true,
						pi.getLabel() + "-" + tabPanel.getTitleAt(i) + " ["
								+ project.getLabel() + "]");
			}
			outputMatrixCBUPanel.selectZoneTab(selectedTab);
			pi = PROJECT_LCOVER_ZONE_CBU_MATRIX;
		} else if (pi == PROJECT_SUMMARY_OPCOST) {
			outputMatrixCBUPanel.setProject(project, DataType.OPCOST);
			holderOutMatrixCBU.setTitle(pi.getAccessibleDescription());
			outputMatrixCBUPanel.setCornerSetting(MenuProperty.UNIT_OPCOST.getLabel(), "", false);
			outputMatrixCBUPanel.setZoneAreaScale(false);
			String s[] = { 
					MenuProperty.PROJECT_ZONE_PARTITION.getLabel(),
					MenuProperty.PROJECT_NET_OPCOST.getLabel(),
					MenuProperty.PROJECT_POSITIVE_OPCOST.getLabel(),
					MenuProperty.PROJECT_NEGATIVE_OPCOST.getLabel()};
			outputMatrixCBUPanel.setLabel(s);

			JTabbedPane tabPanel = outputMatrixCBUPanel.getTabPanel();
			for (int i = 0; i < tabPanel.getTabCount(); i++) {
				LCMatrixOutputPanel c = (LCMatrixOutputPanel) tabPanel
						.getComponentAt(i);
				c.getZonePanel().setMenuDetail(
						true,
						pi.getLabel() + "-" + tabPanel.getTitleAt(i) + " ["
								+ project.getLabel() + "]");
			}
			outputMatrixCBUPanel.selectZoneTab(selectedTab);
			pi = PROJECT_LCOVER_ZONE_CBU_MATRIX;
		} else if (pi == PROJECT_SUMMARY) {
			summaryPanel.setProject(project);
		} else if (pi == PROJECT_ABATEMENT) {
			
			chartContainer.removeAll();
			AbacusPanel chart = projectDock.getProjectManager().getChart(
					project);
			chartContainer.add(chart);
			chart.updateChart();
			
		} else if (pi == MODEL_MAIN || pi == MODEL_TPM
				|| pi == MODEL_LANDUSE_SCENARIO) {
			if (modelPanel.getProject() != project)
				modelPanel.setProject(project, projectDock.getProjectManager());
			
			modelTM.selectZoneTab(selectedTab);
			modelTPM.selectZoneTab(selectedTab);
			modelTM.setSelectUnitArea(true);
		} else if (pi == MODEL_SUMMARY) {

			modelSummaryPanel.setProject(project, getProjectDock()
					.getProjectManager());

		} else if (pi == MODEL_LANDUSE) {
			holderModelOut.setTitle(pi.getAccessibleDescription());
			ModelProject m = project.getModelProject();
			String s[] = { MenuProperty.PROJECT_ZONE_PARTITION.getLabel(), 
					MenuProperty.PROJECT_TOTAL.getLabel() };
			modelIterationPanel.setModelProject(m, DataType.LANDCOVER_CHANGE,
					s, null);
			modelIterationPanel.setCornerSetting(
					MenuProperty.UNIT_FRAC_HA.getLabel(),
					MenuProperty.UNIT_HECTARE.getLabel(),
					true);
			modelIterationPanel.setZoneAreaScale(true);
			modelIterationPanel.selectZoneTab(selectedTab);
			modelIterationPanel.setSelectUnitArea(true);
			pi = MODEL_OUTPUT_MATRIX;

		} else if (pi == MODEL_EMISSION) {
			holderModelOut.setTitle(pi.getAccessibleDescription());
			ModelProject m = project.getModelProject();
			String s[] = {
					MenuProperty.PROJECT_ZONE_PARTITION.getLabel(), 
					MenuProperty.PROJECT_NET_EMISSION.getLabel(), 
					MenuProperty.PROJECT_TOTAL_EMISSION.getLabel(), 
					MenuProperty.PROJECT_TOTAL_SEQ.getLabel() };
			modelIterationPanel.setModelProject(m, DataType.EMISSION, s, null);
			modelIterationPanel.setCornerSetting(MenuProperty.UNIT_EMISSION_HA.getLabel(),
					MenuProperty.UNIT_EMISSION.getLabel(), true);
			modelIterationPanel.setZoneAreaScale(false);
			modelIterationPanel.selectZoneTab(selectedTab);
			modelIterationPanel.setSelectUnitArea(true);
			pi = MODEL_OUTPUT_MATRIX;
		} else if (pi == MODEL_COSTB_TOTAL) {
			holderModelOutCBU.setTitle(pi.getAccessibleDescription());
			String s[] = { MenuProperty.PROJECT_ZONE_PARTITION.getLabel(), 
					MenuProperty.PROJECT_NET_CB.getLabel(),
					MenuProperty.PROJECT_BENEFIT.getLabel(),
					MenuProperty.PROJECT_COST.getLabel() };
			modelOutputCBUPanel.setProject(project, DataType.COSTBENEFIT_TOTAL,
					s);
			modelOutputCBUPanel.setCornerSetting(MenuProperty.UNIT_CB_HA.getLabel(),
					MenuProperty.UNIT_CB.getLabel(), true);
			modelOutputCBUPanel.selectZoneTab(selectedTab);
			pi = MODEL_OUTPUT_CBU_MATRIX;
		} else if (pi == MODEL_OPCOST) {
			holderModelOutCBU.setTitle(pi.getAccessibleDescription());
			String s[] = { MenuProperty.PROJECT_ZONE_PARTITION.getLabel(),
					MenuProperty.PROJECT_NET_OPCOST.getLabel(),
					MenuProperty.PROJECT_POSITIVE_OPCOST.getLabel(),
					MenuProperty.PROJECT_NEGATIVE_OPCOST.getLabel() };
			modelOutputCBUPanel.setProject(project, DataType.OPCOST, s);
			modelOutputCBUPanel.setCornerSetting(MenuProperty.UNIT_OPCOST.getLabel(), "", false);
			modelOutputCBUPanel.selectZoneTab(selectedTab);
			pi = MODEL_OUTPUT_CBU_MATRIX;
		} else if (pi == PROJECT_LCOVER_CHANGE) {
			inputTransitionMatrix.setProject(project);
			if (project.getTotalArea() == 0) {
				int opt = JOptionPane
						.showConfirmDialog(
								inputTransitionMatrix,
								MenuProperty.PROJECT_AREA_ERROR.getAccessibleDescription(),
								MenuProperty.PROJECT_AREA_ERROR.getLabel(),
								JOptionPane.YES_NO_OPTION);
				if (opt == JOptionPane.NO_OPTION) {
					projectDock.setSelection(project, PROJECT_ZONATION);
					return;
				} else {
					isUpdateArea = true;
					ZoneList zones = project.getZoneList();
					project.setTotalArea(zones.getSize());
					for (int i = 0; i < zones.getSize(); i++) {
						zones.get(i).setAreaRatio(1f / zones.getSize());
					}
				}
			}
			inputTransitionMatrix.setEditable(true);
			inputTransitionMatrix.setDataType(DataType.LANDCOVER_CHANGE, null);
			inputTransitionMatrix.setZoneAreaScale(true);
			if (isUpdateArea) {
				inputTransitionMatrix.setCornerSetting(MenuProperty.UNIT_HECTARE.getLabel(), MenuProperty.UNIT_HECTARE.getLabel(),
						false);
			} else {
				inputTransitionMatrix.setCornerSetting(MenuProperty.UNIT_FRAC_HA.getLabel(),
						MenuProperty.UNIT_HECTARE.getLabel(), true);
			}
			inputTransitionMatrix.setSelectUnitArea(true);
			inputTransitionMatrix.selectZoneTab(selectedTab);
			
		} else if (pi == PROJECT_BG_EMISSION) {
			inputBelowgroundEmission.setProject(project);
			inputBelowgroundEmission.setEditable(true);
			inputBelowgroundEmission.setDataType(DataType.BELOWGROUND_EMISSION,	null);
			inputBelowgroundEmission.setZoneAreaScale(false);
			inputBelowgroundEmission.setCornerSetting(MenuProperty.UNIT_EMISSION_HA.getLabel(),
					MenuProperty.UNIT_EMISSION.getLabel(), true);
			inputBelowgroundEmission.selectZoneTab(selectedTab);
			
		} else if (pi == PROJECT_MODIF_EMISSION) {
			inputModifiedEmission.setProject(project);
			inputModifiedEmission.setEditable(true);
			inputModifiedEmission.setDataType(DataType.MODIF_EMISSION, null);
			inputModifiedEmission.setZoneAreaScale(false);
			inputModifiedEmission.setCornerSetting(MenuProperty.UNIT_EMISSION_HA.getLabel(),
					MenuProperty.UNIT_EMISSION.getLabel(), true);
			inputModifiedEmission.selectZoneTab(selectedTab);
			
		} else if (pi == PROJECT_SUMMARY_EMISSION) {
			outputEmissionPanel.setProject(project, DataType.EMISSION, null);
			outputEmissionPanel.getZonePanel().setMenuDetail(
					true,
					PROJECT_SUMMARY_EMISSION.getLabel() + " ["
							+ project.getLabel() + "]");
			outputEmissionPanel.setZoneAreaScale(false);
			outputEmissionPanel.setSelectUnitArea(true);
			outputEmissionPanel.selectZoneTab(selectedTab);
			
		} else if (pi == MODEL_CSTOCK) {
			cstockIterationPanel.setProject(project, DataType.CARBONSTOCK, null);
		} else if (pi == MODEL_NPV) {
			npvIterationPanel.setProject(project, DataType.NPV);
		} else if (pi == MODEL_CB) {
			cbIterationPanel.setProject(project, DataType.COSTBENEFIT_CONVERSION);
			cbIterationPanel.setCornerSetting(MenuProperty.UNIT_CB_HA.getLabel(),
					MenuProperty.UNIT_CB.getLabel(), true);
			cbIterationPanel.setZoneAreaScale(true);
			cbIterationPanel.setEditable(true);
			cbIterationPanel.selectZoneTab(selectedTab);
		} else if (pi == MODEL_BG) {
			bgIterationPanel.setModelProject(project.getModelProject(), DataType.BELOWGROUND_EMISSION, null);
			bgIterationPanel.setZoneAreaScale(false);
			bgIterationPanel.setCornerSetting(MenuProperty.UNIT_EMISSION_HA.getLabel(),
					MenuProperty.UNIT_EMISSION.getLabel(), true);
			bgIterationPanel.selectZoneTab(selectedTab);
		} else if (pi == MODEL_MODIF) {
			modifIterationPanel.setModelProject(project.getModelProject(), DataType.MODIF_EMISSION, null);
			modifIterationPanel.setZoneAreaScale(false);
			modifIterationPanel.setCornerSetting(MenuProperty.UNIT_EMISSION_HA.getLabel(),
					MenuProperty.UNIT_EMISSION.getLabel(), true);
			modifIterationPanel.selectZoneTab(selectedTab);
		}
		card.show(mainPanel, pi.toString());
	}

	private void updateAreaSize(boolean isKeepAreaHectare) {
		ZoneList zones = selectedProject.getZoneList();
		double total = 0;
		double totalFrac = 0;
		for (int i = 0; i < zones.getSize(); i++) {
			total += zones.get(i)
					.getValueTotal(DataType.LANDCOVER_CHANGE, null);
			totalFrac += zones.get(i).getValueTotal(DataType.LANDCOVER_CHANGE,
					null)
					* zones.get(i).getAreaFraction();
		}
		if (isKeepAreaHectare) {
			selectedProject.setTotalArea(totalFrac
					* selectedProject.getTotalArea());
		} else {
			selectedProject.setTotalArea(total);
		}
		for (int i = 0; i < zones.getSize(); i++) {
			double zt = zones.get(i).getValueTotal(DataType.LANDCOVER_CHANGE,
					null);
			if (isKeepAreaHectare) {
				zones.get(i).setAreaRatio(
						zt * zones.get(i).getAreaFraction() / totalFrac);
			} else {
				zones.get(i).setAreaRatio(zt / total);
			}
			zones.get(i).normalizeValue(DataType.LANDCOVER_CHANGE, null);
		}
		isUpdateArea = false;
	}

	public void showProperty(Object childObj, MenuAdapter pi, Project project) {
		card.show(mainPanel, PROGRESS);
		CompBuilder task = new CompBuilder(childObj, pi, project);
		task.execute();

	}
	
	class CompBuilder extends SwingWorker<String, Object> {
		Object childObj;
		MenuAdapter pi;
		Project project;
		
		CompBuilder(Object childObj, MenuAdapter pi, Project project) {
			this.childObj = childObj;
			this.pi = pi;
			this.project = project;
		}

		@Override
		public String doInBackground() {
			doShowProperty(childObj, pi, project);
			return null;
		}

		 @Override
       protected void done() {
			 try {
				
			} catch (Exception e) {

			}
       }
		 
	}




}
